/* eslint-disable array-callback-return,no-undef,prefer-destructuring */
import React, { Component } from 'react';
import { message } from 'antd';
import * as commonConfig from '../../utils/config';
import * as commonUtils from '../../utils/utils'; /* 通用方法 */
import * as commonServices from './../../services/services'; /*   服务类   */
import * as commonFunc from '../Common/commonFunc';

// const { confirm } = Modal;

export default (ChildComponent) => {
  return class extends Component {
    constructor(props) {
      super(props);
      this.state = {};
      this.form = {};
      /*   表单对象   */
    }
    componentWillReceiveProps(nextProps) {
      const { isReceive, importMenuData } = nextProps;
      const { masterConfig } = nextProps;
      if (isReceive === undefined || !isReceive) {
        const exportConfigTypes = [];// importMenuData
        exportConfigTypes.push(commonFunc.getImitateGdsconfigTypes('序号', 'rowIndex', 'rowIndex', false, '', '', false));
        exportConfigTypes.push(commonFunc.getImitateGdsconfigTypes('原因', 'sReason', 'sReason', false, '', '', false));

        this.props.onSaveState({
          isReceive: true,
          pageLoading: false,
        });
        this.handleGetChangeData({ name: 'importMenu' }, 'importMenu');
      }

      if (commonUtils.isNotEmptyArr(importMenuData) && commonUtils.isEmptyObject(masterConfig)) {
        let selectOptions = '{';
        importMenuData.forEach((item, i) => {
          if (i !== 0) { selectOptions = selectOptions.concat(','); }
          selectOptions = selectOptions.concat(`"${item.gdsconfigformmasterId}"`).concat(':').concat(`"${item.sMenuName}"`);
        });
        selectOptions = selectOptions.concat('}');

        const exportConfigTypes = [];// importMenuData
        exportConfigTypes.push(commonFunc.getImitateGdsconfigTypes('数据模板', 'sTemplate', 'sTemplate', false, 'const', selectOptions, false));
        exportConfigTypes.push(commonFunc.getImitateGdsconfigTypes('导出模板', 'btnExport', '', false, '', '', false));

        const importConfigTypes = [];
        importConfigTypes.push(commonFunc.getImitateGdsconfigTypes('导入表', 'sMasterId', 'sMasterId', false, 'const', selectOptions, false));
        importConfigTypes.push(commonFunc.getImitateGdsconfigTypes('上传校验', 'btnUpload', '', false, '', '', true));
        importConfigTypes.push(commonFunc.getImitateGdsconfigTypes('导入数据', 'btnSave', '', false, '', '', false));
        const currConfig = {};
        currConfig.rowGdsconfig = [{ gdsconfigformslave: exportConfigTypes }, { gdsconfigformslave: importConfigTypes }];

        const masterData = {};
        masterData.handleType = '';
        masterData.sId = commonUtils.createSid();

        this.props.onSaveState({
          enabled: true,
          masterData,
          masterConfig: currConfig,
        });
      }
    }

    shouldComponentUpdate(nextProps, nextState) {
      let flag = true;
      /* 追加弹出框数值回填放行判断ppopupPane */
      if (nextProps.sTabId === nextProps.app.currentPane.key || ((nextProps.app.ppopupPane !== undefined
          && nextProps.app.ppopupPane.mainConfig !== undefined)
        ? nextProps.sTabId === nextProps.app.ppopupPane.mainConfig.key : false)) {
        if (nextState.disabled !== this.state.disabled) {
          return true;
        }
        flag = true;
      } else {
        flag = false;
      }
      return flag;
    }

    /**   表单回带   */
    handleForm = (form) => {
      this.form = form;
    };
    /** 主表控件是否全部显示 */
    handleToggle = () => {
      const { expand } = this.props;
      this.props.onSaveState({ expand: !expand });
    };
    /* save */
    handleValidateSave = async () => {
      const {
        token, sModelsId, sJurisdictionClassifyId, sUserId, treeSaveParams,
      } = this.props;
      const value = {};
      if ((commonUtils.isEmptyArr(sJurisdictionClassifyId) || commonUtils.isEmptyArr(sUserId)) && commonUtils.isEmptyArr(treeSaveParams)) {
        message.warn('组员，所属或权限组不能为空!');
        return;
      }
      value.data = treeSaveParams;
      const dataUrl = `${commonConfig.server_host}/sysjurisdiction/addSysjurisdiction?sModelsId=${sModelsId}`;
      const dataReturn = (await commonServices.postValueService(token, value, dataUrl)).data;
      /*   成功的话返回数据   */
      if (dataReturn.code === 1) { /*   成功   */
        message.success(dataReturn.msg);
        return dataReturn;
      } else { /*   失败   */
        message.error(dataReturn.msg);
        return false;
      }
    }

    /* get */
    handleGetChangeData = async (params, urlKey) => {
      const { app, sModelsId } = this.props;
      const { token } = app;
      const { name, gdsconfigformmasterId } = params; // name,
      let dataUrl = '';// ImportMenu
      if (urlKey === 'importMenu') { // yw_获取导入模板菜单
        dataUrl = `${commonConfig.server_host}import/getImportMenu?sModelsId=${sModelsId}`;
      } else if (urlKey === 'exportTemplet') { // yw_导出将要导入的模板execl
        dataUrl = `${commonConfig.server_host}import/exportTemplet?gdsconfigformmasterId=${gdsconfigformmasterId}&token=${token}`;
      }
      const dataReturn = (await commonServices.getService(token, dataUrl)).data;
      if (dataReturn.code === 1) {
        const returnData = dataReturn.dataset.rows;
        this.props.onSaveState({ [`${name}Data`]: returnData });
      } else {
        message.error(dataReturn.msg);
      }
    }

    /* post */
    handlePostData = async (params, urlKey) => {
      const { app, sModelsId } = this.props;
      const { token } = app;
      const {
        name, gdsconfigformmasterId, file, execlData, sTableName,
      } = params; // name,
      let dataUrl = '';
      const value = {};
      if (urlKey === 'checkExcel') { // yw_校验导入模板数据
        value.gdsconfigformmasterId = gdsconfigformmasterId;
        value.file = file;
        dataUrl = `${commonConfig.server_host}import/checkExcel?sModelsId=${sModelsId}`;
      } else if (urlKey === 'addImport') {
        dataUrl = `${commonConfig.server_host}import/addImport?sModelsId=${sModelsId}`;
        value.sTableName = sTableName;
        value.execlData = execlData;
      }

      const dataReturn = (await commonServices.postValueService(token, value, dataUrl)).data;

      if (dataReturn.code === 1) {
        if (urlKey === 'checkExcel') {
          const returnData = dataReturn.dataset.rows;
          const allInitArr = [];
          const allInitMap = new Map();
          this.handleAllCheckKeys(allInitArr, allInitMap, returnData);
          this.props.onSaveState({ [`${name}Data`]: returnData, treeAllCheckKeys: allInitArr, treeAllNodes: allInitMap });
        } else if (urlKey === 'addImport') {
          message.info(dataReturn.msg);
        }
      } else {
        message.error(dataReturn.msg);
      }
    }

    // 模拟 列
    imitateTableColumn = (title, dataIndex, key, selectData) => {
      return {
        title, dataIndex, key, selectData,
      };
    }
    // 模拟config的 gdsconfigformslave 配置
    imitateMasterFiledConfig = (title, dataIndex, selectData) => {
      return {
        sBrandsId: '1111111111',
        sChinese: title,
        sChineseDropDown: '',
        sControlName: 'BtnLast',
        sId: commonUtils.createSid(),
        sParentId: '11811781131121915102156308120',
        sSubsidiaryId: '1111111111',
        showName: title,
        sName: dataIndex,
        dropDownData: selectData === undefined ? [] : selectData,
      };
    }
    // 根据模拟列，模拟列配置
    imitateTableColumnConfig = (name, columns) => {
      const gdsconfigformslave = [];
      columns.forEach((itmes) => {
        gdsconfigformslave.push(this.imitateTableConfig(itmes.title, itmes.dataIndex, itmes.dropDownData));
      });
      const config = { bGrd: true, gdsconfigformslave };
      return { [`${name}Column`]: columns, [`${name}Config`]: config };
    }
    /** 修改主表数据 */
    handleMasterChange = (name, sFieldName, changeValue, sId, dropDownData) => {
      const addState = this.props.onChange(name, sFieldName, changeValue, sId, dropDownData, true);
      const gdsconfigformmasterId = {};
      if (sFieldName === 'sMasterId') {
        addState.gdsconfigformmasterId = changeValue[sFieldName];
      }
      this.props.onSaveState({ gdsconfigformmasterId, ...addState });
    };

    handleUploadChange = (sControlName, info) => {
      /* 获取上传后的一些信息 */
      const { file } = info;
      let { [`${sControlName}UploadInfo`]: uploads } = this.props;
      if (commonUtils.isEmptyArr(uploads)) {
        uploads = [];
        uploads.push(file);
      } else {
        uploads.push(file);
      }
      this.props.onSaveState({ [`${sControlName}UploadInfo`]: uploads });
    };

    /* 按钮点击功能  */
    handleBtnClick = (e, btnName) => {
      const {
        masterData, app, canbeInsertData, nocanbeInsertData, sTableName,
      } = this.props;
      const { token } = app;
      const { sTemplate } = masterData;
      if (btnName === 'btnExport') {
        if (commonUtils.isNotEmptyObject(masterData) && commonUtils.isNotEmptyObject(sTemplate)) {
          window.location.href = `${commonConfig.server_host}import/exportTemplet?gdsconfigformmasterId=${sTemplate}&token=${token}`;
        } else {
          message.error('请选择要导出的模板');
        }
      } else if (btnName === 'btnSave') {
        if (commonUtils.isEmptyArr(nocanbeInsertData) && commonUtils.isNotEmptyArr(canbeInsertData) && commonUtils.isNotEmptyObject(sTableName)) {
          this.handlePostData({ name: 'addImport', execlData: canbeInsertData, sTableName }, 'addImport');
        } else {
          message.error('请等待数据校验完成');
        }
      }
    };

    /* 按钮点击功能  */
    handleShowUploadData = (response, sControlName) => {
      console.log('btn:', sControlName);
      if (response.code === 1) {
        const returnData = response.dataset.rows[0];
        const {
          nocanbeInsert, canbeInsert, titleList, sTableName,
        } = returnData;
        const configTypes = [];// importMenuData
        configTypes.push(commonFunc.getImitateGdsconfigTypes('原因', 'sReason', 'sReason', false, '', '', false));

        const config = { gdsconfigformslave: configTypes.concat(titleList) };
        const configInsert = { gdsconfigformslave: titleList };
        const slavesColumn = commonFunc.getHeaderConfig(config);
        this.props.onSaveState({
          sTableName,
          nocanbeInsertData: nocanbeInsert,
          canbeInsertData: canbeInsert,
          nocanbeInsertConfig: config,
          nocanbeInsertColumn: slavesColumn,
          canbeInsertColumn: slavesColumn,
          canbeInsertConfig: configInsert,
        });
      } else {
        message.error(response.msg);
      }
    };

    handleCreatUploadUrl = (sControlName) => {
      const { masterData, app } = this.props;
      const { sMasterId } = masterData;
      const { token } = app;
      let action = '';
      if (sControlName === 'btnUpload') {
        action = `${commonConfig.server_host}import/exportTemplet?gdsconfigformmasterId=${sMasterId}&token=${token}`;
      }
      return action;
    }
    render() {
      return (
        <ChildComponent
          {...this.props}
          {...this.state}
          onReturnForm={this.handleForm}
          onToggle={this.handleToggle}
          onSubmit={this.handleValidateSave}
          onDataChange={this.handleTableChange}
          onChange={this.handleMasterChange}
          onUploadChange={this.handleUploadChange}
          onBtnClick={this.handleBtnClick}
          onShowData={this.handleShowUploadData}
        />
      );
    }
  };
};
